package com.tkm.types.eg

import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
import java.io.File

//  定义网络请求接口
interface GithubApi {
    @GET("/repos/{owner}/{repo}")
    fun getRepository(
        @Path("owner") owner: String,
        @Path("repo") repo: String
    ): Call<Repository>
}

fun main() {
    //  构建Retrofit实例
    val githubApi = Retrofit.Builder()
        .baseUrl("https://api.github.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()
        .create(GithubApi::class.java)
    //  网络请求
    //  此处使用阻塞方式请求，仅为演示，实际开发中，要使用非阻塞式请求
    val response = githubApi.getRepository("Jetbrains", "Kotlin").execute()
    val repository = response.body()
    if (repository == null) {
        println("request failed: ${response.code()}")
    } else {
        //  writeText：Kotlin为File拓展的方法，方便写入文件
        File("eg.html").writeText("""
            <!DOCTYPE html>
            <html>
                <head>
                    <meta charset="utf-8">
                    <title>${repository.owner.login} - ${repository.name}</title>
                    <style>
                        * {
                            margin: 0;
                            padding: 0;
                        }
                    </style>
                </head>
                <body>
                    <h1>
                        <a href='${repository.html_url}'>
                            ${repository.owner.login} - ${repository.name}
                        </a>
                    </h1>
                    <p>${repository.description}</p>
                    <p>Stars: ${repository.stargazers_count}</p>
                    <p>Forks: ${repository.forks_count}</p>
                </body>
            </html>
        """.trimIndent())

        val html = File("eg.html").readText()
        println(html)
    }
}
